<template>
  <div class="mainua">
    <el-form
      class="demo-form-inline"
      :model="form"
      label-width="110px"
      ref="form"
      :rules="rules"
    >
      <div class="main_spac1" style="padding-bottom: 5px">
        <div class="main_white padding10">
          <div class="main_crumbs boxdq">
            <div class="main_crumbs_l">
              <a href="javascript:;" @click="$router.back(-1)">
                <i class="el-icon-arrow-down"></i>返回
              </a>
              <em>|</em>
              <span>限时特卖</span>
            </div>
          </div>
          <!-- 主要部分 -->
          <div v-loading="loading" element-loading-text="加载中...">
            <div class="marginTop20 marginLeft25">
              <el-form-item label="活动名称：" prop="name">
                <el-input
                  class="wid240"
                  v-model="form.name"
                  placeholder="活动名称"
                  @change="isEdit = true"
                ></el-input>
              </el-form-item>
              <el-form-item label="活动时间：" prop="time">
                <el-date-picker
                  v-model="form.time"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  @change="changeTime"
                  :picker-options="pickerOptions"
                >
                </el-date-picker>
              </el-form-item>
              <el-form-item label="用户分组：" prop="group_ids">
                <el-select
                  class="wid240"
                  v-model="form.group_ids"
                  placeholder="用户分组"
                  multiple
                  @change="changeGroup"
                >
                  <el-option label="全部" value="-1"></el-option>
                  <el-option
                    v-for="(item, index) in group"
                    :label="item"
                    :value="index"
                    :key="index"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="" prop="is_impact">
                <div slot="label">
                  周期报价
                  <el-tooltip
                    class="item marginRight5 mainor_tei"
                    effect="dark"
                    placement="bottom"
                  >
                    <div slot="content">
                      注释：使用周期报价用户的商品价格、起订量、系统库存将不会参与该活动
                    </div>
                    <i class="el-icon-question"></i> </el-tooltip
                  >：
                </div>
                <el-radio-group
                  v-model="form.is_impact"
                  @change="isEdit = true"
                >
                  <el-radio :label="0">不影响</el-radio>
                  <el-radio :label="1">影响</el-radio>
                </el-radio-group>
              </el-form-item>

              <el-form-item label="" prop="is_limit">
                <div slot="label">
                  限购规则
                  <el-tooltip
                    class="item marginRight5 mainor_tei"
                    effect="dark"
                    placement="bottom"
                  >
                    <div slot="content">
                      注释：活动时间内，是否限制用户购买数量
                    </div>
                    <i class="el-icon-question"></i> </el-tooltip
                  >：
                </div>
                <el-radio-group v-model="form.is_limit" @change="isEdit = true">
                  <el-radio :label="0">不限购</el-radio>
                  <el-radio :label="1">限购</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="" prop="type">
                <div slot="label">
                  限购类型
                  <el-tooltip
                    class="item marginRight5 mainor_tei"
                    effect="dark"
                    placement="bottom"
                  >
                    <div slot="content">
                      注释：严格类型即达到限购数量后不可再下单，<br />宽松类型即达到限购数量后仍然可以下单，<br />只是后续数量不享受活动价格
                    </div>
                    <i class="el-icon-question"></i> </el-tooltip
                  >：
                </div>
                <el-radio-group v-model="form.type">
                  <el-radio :label="1">严格</el-radio>
                  <el-radio :label="2">宽松</el-radio>
                </el-radio-group>
              </el-form-item>
            </div>

            <div class="goods_container marginLeft20 marginRight20" v-if="true">
              <div class="goods_container_header">
                <el-form-item label="商品名称：">
                  <el-autocomplete
                    v-model="formsp.value"
                    ref="searchSelect"
                    class="wid240 main_comm"
                    :trigger-on-focus="false"
                    @clear="$refs.searchSelect.$children[0].blur()"
                    :fetch-suggestions="
                      (queryString, cb) => {
                        querySearchAsync(queryString, cb);
                      }
                    "
                    placeholder="商品/助记码/编码"
                    clearable
                    :highlight-first-item="true"
                    value-key="name"
                    @select="
                      (item) => {
                        handleSelect(item);
                      }
                    "
                  >
                    <template slot-scope="{ item }">
                      <div class="main_name">
                        <span
                          >{{ item.goods.name }}【{{
                            item.spu_name ? item.spu_name.title : ""
                          }}】</span
                        >
                        <span class="main_addr">{{ item.goods_spu_code }}</span>
                      </div>
                    </template>
                  </el-autocomplete>
                </el-form-item>
                <el-form-item
                  label="价格："
                  label-width="60px"
                  class="num_lable"
                >
                  <el-input
                    v-model.trim="formsp.num"
                    ref="focusw2"
                    placeholder="价格"
                    clearable
                    class="wid140"
                    @keyup.enter.native="mainor_sp"
                  ></el-input>
                </el-form-item>
                <div class="btns">
                  <el-button type="primary" @click="mainor_qr"
                    >确认(回车)</el-button
                  >
                  <el-button
                    class="reset marginLeft5"
                    @click="reset"
                    >重置</el-button
                  >
                </div>
              </div>
              <div class="goods_container_body main_taf main_table">
                <el-table
                  ref="multipleTable"
                  :data="form.list"
                  element-loading-text="加载中"
                  fit
                  border
                  highlight-current-row
                >
                  <el-table-column label="序号" width="80">
                    <template slot-scope="scope">{{
                      scope.$index + 1
                    }}</template>
                  </el-table-column>
                  <el-table-column
                    label="商品名称"
                    prop="goods_name"
                    :show-overflow-tooltip="true"
                  />
                  <el-table-column
                    label="单位"
                    prop="unit"
                    :show-overflow-tooltip="true"
                  >
                  </el-table-column>
                  <el-table-column
                    label="最近一次采购价"
                    prop="purchase_price"
                    :show-overflow-tooltip="true"
                  />
                  <el-table-column
                    label="市场价"
                    prop="market_price"
                    :show-overflow-tooltip="true"
                  />
                  <el-table-column label="活动价格" prop="price">
                    <template slot-scope="scope">
                      <el-form-item
                        label-width="10px"
                        label=" "
                        :prop="'list.' + scope.$index + '.price'"
                        :rules="rules.price"
                      >
                        <el-input
                          v-model.trim="scope.row.price"
                          :ref="'price' + scope.row.price"
                          placeholder="单价"
                          class="wid120"
                          @change="(val) => changeNumber(val, scope, 1)"
                        ></el-input>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column label="用户限购" prop="num_limit">
                    <template slot-scope="scope">
                      <el-form-item
                        label-width="10px"
                        label=" "
                        v-if="form.is_limit == 0"
                      >
                        <el-input
                          v-model.trim="num_limit_title"
                          :ref="'order_price' + scope.row.num_limit"
                          :disabled="form.is_limit == 0"
                          placeholder="不限购"
                          class="wid120"
                        ></el-input>
                      </el-form-item>
                      <el-form-item
                        label-width="10px"
                        label=" "
                        v-show="form.is_limit == 1"
                        :prop="'list.' + scope.$index + '.num_limit'"
                        :rules="form.is_limit == 1 ? rules.num_limit : []"
                      >
                        <el-input
                          v-model.trim="scope.row.num_limit"
                          :ref="'num_limit' + scope.row.num_limit"
                          placeholder="请输入限购数量"
                          class="wid120"
                          @change="(val) => changeNumber(val, scope, 2)"
                        ></el-input>
                      </el-form-item> </template
                  ></el-table-column>
                  <el-table-column label="起订量" prop="minimum">
                    <template slot-scope="scope">
                      <el-form-item
                        label-width="10px"
                        label=" "
                        :prop="'list.' + scope.$index + '.minimum'"
                        :rules="rules.minimum"
                      >
                        <el-input
                          v-model.trim="scope.row.minimum"
                          :ref="'minimum' + scope.row.minimum"
                          @change="(val) => changeNumber(val, scope, 3)"
                          placeholder="起订量"
                          class="wid120"
                        ></el-input>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column label="活动库存" prop="inventory">
                    <template slot-scope="scope">
                      <el-form-item
                        label-width="10px"
                        label=" "
                        :prop="'list.' + scope.$index + '.inventory'"
                        :rules="rules.inventory"
                      >
                        <el-input
                          v-model.trim="scope.row.inventory"
                          :ref="'order_price' + scope.row.inventory"
                          placeholder="活动库存"
                          class="wid120"
                          @change="(val) => changeNumber(val, scope, 4)"
                        ></el-input>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="管理操作"
                    prop="name"
                    width="160"
                    align="center"
                    fixed="right"
                    :show-overflow-tooltip="true"
                  >
                    <template slot-scope="scope">
                      <el-link @click="handeleDel(scope.row, scope.$index)"
                        >删除</el-link
                      >
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
            <div class="clearfix"></div>
            <div class="paddingBottom10" id="newConBox">
              <div class="newConBox_h32">
                <div :class="['boxdq newConBox ', { on: searchBarFixed }]">
                  <div class="mainor_prl">
                    <el-button
                      type="primary"
                      class="mg-r-6"
                      @click="preservation"
                      v-repeatClick
                      :loading="save_loading"
                      >保存</el-button
                    >
                    <el-button
                      class="reset"
                      v-repeatClick
                      @click="$router.back(-1)"
                      >取消</el-button
                    >
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-form>
  </div>
</template>
<script>
import rules from "@/rules/marketing/marketing_timelimit.js";
import { get_full_getGoodsSpu } from "@/api/marketing/marketing.js";
import {
  get_panic_base,
  get_panic_info,
  get_panic_edit,
  get_panic_add,
  get_deleteList,
} from "@/api/marketing/marketing_timelimit.js";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";
import { parseTime } from "@/utils/index";

export default {
  name: "",
  data() {
    return {
      rules,
      parseTime,
      id: "",
      form: {
        name: "",
        type: 1, //  1  严格模式  2宽松模式
        group_ids: "", //分组id
        time: [],
        start_time: "",
        end_time: "",
        is_impact: 0, // 0  不影响周期报价  1  影响
        is_limit: 0, //0 不限购  1 限购
        num: "", //限购数量
        list: [],
      },
      addtype: "",
      list: [],
      num_limit_title: "",
      // 监听滚动
      searchBarFixed: false,
      goods_name: "",
      num: "",
      formsp: {
        goods: "",
        num: "",
        value: "",
        girard: "",
      },
      group: {},
      pickerOptions: {
        disabledDate(time) {
          let now = new Date();
          now.setHours(0);
          now.setMinutes(0);
          now.setSeconds(0);
          now.setMilliseconds(0);
          return time.getTime() < now.getTime();
        },
      },
      save_loading: false,
      loading: false,
      isEdit: false,
    };
  },
  methods: {
    checkDeductionRate(rule, value, callback) {
      if (!value) {
        callback(new Error("用户限购数量不能为空"));
      } else {
        callback();
      }
    },
    // 监听滚动
    handleScroll() {
      let scrollTop =
        window.pageYOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop;
      scrollTop + document.documentElement.clientHeight >
      document.getElementById("newConBox").offsetTop + 240
        ? (this.searchBarFixed = false)
        : (this.searchBarFixed = true);
    },
    // 获取商品
    querySearchAsync(queryString, cb) {
      let name = queryString || "";
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        {
          name: name,
          status: 1,
        }
      );
      get_full_getGoodsSpu(data).then((res) => {
        if (res.errcode == 0) {
          if (this.$refs.searchSelect) {
            this.$refs.searchSelect.activated = true;
          }
          res.data.list.map((e) => {
            e.name = `${e.goods.name}【${e.spu_unit.title}】`;
          });
          var results = res.data.list;
          cb(results);
        } else {
          this.$message.error(res.errmsg);
          cb([]);
        }
      });
    },
    // 活动时间选择
    changeTime(val) {
      this.isEdit = true;
      if (val.length > 0) {
        if (val[0] == val[1]) {
          this.$message.error("活动开始时间不能等于结束时间");
          this.form.time = [];
        }
      }
    },
    // 商品选择
    handleSelect(item) {
      this.isEdit = true;
      this.formsp.goods = item;
      this.formsp.girard = item.id;
      setTimeout(() => {
        this.$refs.focusw2.focus();
      }, 100);
    },
    // 商品选择确认(回车)
    mainor_sp(e) {
      var keyCode = window.event ? e.keyCode : e.which;
      if (keyCode == 13) {
        this.mainor_qr();
      }
    },
    // 点击添加
    mainor_qr() {
      this.isEdit = true;
      let formsp = JSON.parse(JSON.stringify(this.formsp));
      if (!formsp.value) {
        this.$message.error("请填写商品名称");
        this.$refs.searchSelect.focus();
        return;
      } else if (formsp.num == "") {
        this.$message.error("请填写数量");
        this.$refs.focusw2.focus();
        return;
      } else {
        let item = this.formsp.goods;
        let obj = {
          goods_name: `${item.goods.name}【${item.spu_name.title}】`,
          goods_id: item.goods_id,
          goods_spu_id: item.id,
          unit: item.spu_unit ? item.spu_unit.title : "",
          purchase_price: item.purchase_price, //采购价
          market_price: item.market_price, //市场价
          price: formsp.num, //设置价格
          num_limit: "",
          inventory: 0, //设置库存
          minimum: 0, //起订量
        };
        let ind = 0;
        let index = 0;
        if (this.form.list.length != 0) {
          this.form.list.map((e, index) => {
            if (e.goods_spu_id == formsp.girard) {
              ind = e.goods_spu_id;
              return;
            }
          });
          if (ind == 0) {
            this.form.list.push(obj);
            this.reset();
            setTimeout(() => {
              this.$refs.searchSelect.focus();
            }, 100);
          } else {
            this.reset();
            this.$refs.searchSelect.focus();
          }
        } else {
          this.form.list.push(obj);
          this.reset();
          setTimeout(() => {
            this.$refs.searchSelect.focus();
          }, 100);
        }
      }
    },
    // 重置
    reset() {
      this.isEdit = true;
      this.formsp.goods = "";
      this.formsp.num = "";
      this.formsp.value = "";
      this.formsp.girard = "";
    },
    handeleDel(row, index) {
      this.form.list.splice(index, 1);
      // let id = row.list_id;
      // let data = Object.assign(
      //   {
      //     sign: Md5(
      //       objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
      //     ),
      //   },
      //   apiUrl().name,
      //   { id: id }
      // );
      // get_deleteList(data).then((res) => {
      //   if (res.errcode == 0) {
      //   } else {
      //     this.$message.error(res.errmsg);
      //     this.get_panic_info();
      //   }
      // });
    },
    // 保存按钮事件
    preservation() {
      this.$refs["form"].validate(async (valid) => {
        if (valid) {
          let response = await this.handleForm();
          if (!response) {
            return;
          }

          if (this.addtype) {
            this.get_panic_add(response);
          } else {
            this.get_panic_edit(response);
          }
        } else {
        }
      });
    },
    // 处理数据
    async handleForm() {
      let response = JSON.parse(JSON.stringify(this.form));

      if (response.time[0]) {
        response.start_time = response.time[0];
      }
      if (response.time[1]) {
        response.end_time = response.time[1];
      }
      if (response.group_ids.length && response.group_ids[0] == "-1") {
        response.group_ids = Object.keys(this.group);
      }
      response.group_ids = response.group_ids.join(",");
      let flag = false;
      let list = response.list.map((e) => {
        if (response.is_limit == 0) {
          e.num_limit = 0;
        }
        if (response.is_limit == 1) {
          if (e.num_limit == null || e.num_limit == "") {
            flag = true;
          }
        }
        let { goods_name, unit, purchase_price, list_id, ...sz } = e;
        return {
          ...sz,
        };
      });
      if (flag) {
        this.$message.warning("限购条件下，请输入限购数量");
        return false;
      }
      delete response.time;
      delete response.num;
      response.list = JSON.stringify(list);
      return response;
    },
    // 编辑保存
    get_panic_edit(response) {
      this.save_loading = true;
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        response,
        { id: this.id }
      );
      get_panic_edit(data).then((res) => {
        this.save_loading = false;
        if (res.errcode == 0) {
          this.$message.success("编辑成功");
          this.isEdit = false;
          this.$router.back(-1);
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 复制新增保存
    get_panic_add(response) {
      this.save_loading = true;
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        response
      );
      get_panic_add(data).then((res) => {
        this.save_loading = false;
        if (res.errcode == 0) {
          this.$message.success("新增成功");
          this.isEdit = false;
          this.$router.back(-1);
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 获取用户分组
    get_panic_base() {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name
      );
      get_panic_base(data).then((res) => {
        if (res.errcode == 0) {
          this.group = res.data.group;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    changeGroup(val) {
      if (val.indexOf("-1") != -1) {
        this.form.group_ids = ["-1"];
      }
    },
    changeNumber(val, scope, type) {
      if (!/^-?\d*\.?\d*$/.test(val)) {
        this.$message.error("请输入数字");
        return;
      }

      if (this.form.is_limit == 1) {
        if (Number(scope.row.minimum) > Number(scope.row.num_limit)) {
          this.$message.warning("起订量需要小于等于用户限购量");
          scope.row.minimum = scope.row.num_limit;
        }
      }
    },
    // 获取信息
    get_panic_info() {
      this.loading = true;
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { id: this.id }
      );
      get_panic_info(data).then((res) => {
        if (res.errcode == 0) {
          let info = res.data.info;
          this.form.name = info.name;
          let time1 = this.parseTime(info.start_time);
          let time2 = this.parseTime(info.end_time);
          this.form.time = [time1, time2];
          this.form.is_impact = info.is_impact;
          this.form.is_limit = info.is_limit;
          this.form.type = info.type;
          let group_ids = info.group_ids.split(",");
          this.form.group_ids = group_ids.map(String);
          let list = [];
          info.panic_buy_list.map((e) => {
            let obj = {
              id: e.id,
              goods_name: `${e.goods.name}【${e.goods_spu.spu_unit.title}】`,
              goods_id: e.goods_id,
              goods_spu_id: e.goods_spu_id,
              unit: e.goods_spu.spu_unit ? e.goods_spu.spu_unit.title : "",
              purchase_price: e.goods_spu.purchase_price, //采购价
              market_price: e.market_price, //市场价
              price: e.price, //设置价格
              num_limit: info.is_limit == 1 ? e.num_limit : "",
              inventory: e.inventory, //设置库存
              minimum: e.minimum, //起订量
              list_id: e.id,
            };
            list.push(obj);
          });
          this.form.list = list;
          this.loading = false;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
  },
  created() {
    this.id = this.$route.params.id;
    if (this.$route.query.type) {
      this.addtype = this.$route.query.type;
    }
    this.get_panic_base();
    this.get_panic_info();
  },
  beforeRouteLeave(to, from, next) {
    if (this.isEdit) {
      setTimeout(() => {
        this.$confirm(
          "您已经有数据操作，离开页面系统不会保存您的操作，确定离开吗？",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(() => {
            next();
          })
          .catch(() => {
            next(false);
          });
      }, 200);
    } else {
      next();
    }
  },
  mounted() {
    window.addEventListener("scroll", this.handleScroll);
    let scrollTop =
      window.pageYOffset ||
      document.documentElement.scrollTop ||
      document.body.scrollTop;

    scrollTop + document.documentElement.clientHeight >
    document.getElementById("newConBox").offsetTop + 250
      ? (this.searchBarFixed = false)
      : (this.searchBarFixed = true);
  },
  destroyed() {
    window.removeEventListener("scroll", this.handleScroll);
  },
};
</script>
<style lang='scss' scoped>
.validity {
  display: flex;
  align-items: center;
  flex-direction: row;
  &:first-child {
    margin-bottom: 18px;
  }
  /deep/.el-button--info {
    color: #fff;
  }
  /deep/ .el-form-item--mini.el-form-item,
  .el-form-item--small.el-form-item {
    margin-bottom: 0;
  }
  /deep/ .el-radio {
    margin-right: 10px;
    transform: translateY(1px);
  }
  span {
    font-size: 14px;
    color: #606266;
    display: inline-block;
    // padding-left: 15px;
    &.span1 {
      padding-left: 15px;
      padding-right: 10px;
    }
    &.span2 {
      padding-left: 10px;
    }
  }
}
.limit_number {
  margin: 0 10px;
}
.save_container {
  padding: 0 20px;
  margin-top: 15px;
  &.positive {
    position: fixed;
    bottom: 50px;
    left: 0;
    z-index: 9999;
  }
}
#newConBox {
  margin-top: 15px;
  padding-left: 20px;
}
.newConBox.on {
  margin-left: -10px;
  padding-left: 10px;
  bottom: 70px;
  border-top: 0;
  width: auto;
}
.goods_container_header {
  display: flex;
  align-items: flex-start;
  .btns {
    padding-left: 10px;
  }
}

.main_table /deep/ .el-table--small td .cell {
  height: auto;
  .el-form-item--mini.el-form-item,
  .el-form-item--small.el-form-item {
    margin-top: 10px;
  }
}
.main_table /deep/ .el-table--small td {
  padding: 0;
}
.main_name {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 5px 0;
  height: 50px;

  .main_addr {
    color: #999;
  }

  span {
    line-height: 20px;
    display: inline;
    height: 20px;
  }
}
</style>
